#!usr/bin/node

const http = require('http'),
      items = [];

function genPage() {
  let html = `
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8" />
    <title>todo list</title>
    </head>
    <body>
    <h1>Todo List</h1>
    <form method='POST' action='/'>
    <input type='text' name='item'>
    <input type='submit' value='submit'>
    </form>
    <ul>%</ul>
    </body>
    </html>`;
  const dom = items.map(item => `<li>${item}</li>`).join('');

  html = html.replace('%',dom);
  return html;
}

http.createServer((req,res) => {
  //get pathname
  const url = new URL(req.url,`http://${req.headers.host}`),
        pathname = url.pathname;

  let item = '';

  if(req.url === '/') {
    if(req.method === 'POST') {
      req.on('data',chunk => {
        item += chunk;
      })
      req.on('end',() => {
        item = new URLSearchParams(item);
        item = item.get('item');
        if(item !== null && item !== '') {
          items.push(item)
        }
        res.end(genPage());
      })
      }else if(req.method === 'GET') {
        res.end(genPage());
      }else{
        res.statusCode = 404;
        res.end('Request method not supported')
      }
  }
}).listen(8080);

